package org.jiamandan.com.strategy.impl.charge.device;


import cn.hutool.core.util.StrUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jiamandan.com.constant.BizConstant;
import org.jiamandan.com.constant.ChargeConstant;
import org.jiamandan.com.dto.OrderDto;
import org.jiamandan.com.entity.RechargePile;
import org.jiamandan.com.strategy.IChargeBaseService;
import org.jiamandan.com.utils.CommonUtil;
import org.jiamandan.com.utils.ZDObjectUtil;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;


@Service(value = ChargeConstant.Service.YD_SERVICE)
@AllArgsConstructor
@Slf4j
public class YdChargeListener extends IChargeBaseService {

    @Override
    public void issueCharge(OrderDto dto, Channel channel) throws Exception {
        log.info("下发充电设备号【" + dto.getPileNo() + "】充电时长：" + dto.getMaxChargeTime() + "，最大功率：" + dto.getMaxPower());
        RechargePile pile = new RechargePile();
        pile.setCode(4);
        pile.setPileNo(dto.getPileNo());
        if (dto.getPileNo() != null) {
            StringBuilder payload = new StringBuilder();
            payload.append("00")
                    .append(CommonUtil.reverseHex(StringUtils.leftPad(Integer.toHexString(dto.getChargeAmt().multiply(BigDecimal.valueOf(100)).intValue()), 8, "0")))
                    .append(StringUtils.leftPad(StrUtil.toString(Integer.valueOf(dto.getGunNo()) - 1), 2, "0"))
                    //充电命令=0(停止充电)，=1(开始充电)设备充电与否依据此字段
                    .append("01")
                    .append("0000")
                    .append(StringUtils.leftPad(dto.getTradeNo(), 32, "0"))
                    //最大充电时长 先按照 最高功率计算费用下发最大时间，后06指令获取实际最高功率重新计算时间08指令下发
                    .append(CommonUtil.reverseHex(StringUtils.leftPad(Integer.toHexString(dto.getMaxChargeTime()), 4, "0")))
                    //最大1000功率
                    .append(CommonUtil.reverseHex(StringUtils.leftPad(Integer.toHexString(dto.getMaxPower() * 10), 4, "0")))
                    .append("01")
                    .append("00")
                    .append("0000");//额外增加的浮充时间，单位秒，如果下发的是0xFFFF，则为取消浮充
            String replyMsg = ZDObjectUtil.ydsplicingMessage(payload.toString(), pile,dto.getGunNo(), BizConstant.Cmd.CMD_YD_82);
            log.info("JMD-YD下发充电或停止(CMD=82)设备号【" + dto.getPileNo() + "】报文:" + replyMsg);
            ByteBuf buf = Unpooled.buffer(replyMsg.getBytes().length);
            buf.writeBytes(CommonUtil.hexToByteArray(replyMsg));
            ChannelFuture future = channel.writeAndFlush(buf);
        }
    }
}
